<?php

namespace app\api\controller;

use app\api\model\Cases;
use app\api\model\PatrolLog;
use app\api\validate\PatrolChildValidate;
use app\api\validate\PatrolValidate;
use app\common\controller\Api;
use think\Config;
use think\Exception;

/**
 * 巡查街道
 */
class PatrolChild extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    protected $failException = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\api\model\PatrolChild();
        $this->modelPatrol = new \app\api\model\Patrol();
        $this->modelLog = new PatrolLog();
        $this->modelCases = new Cases();
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }


    /**
     * 列表
     * @return void
     */
    public function list()
    {
        $input = input();
        try {
            $where = [];
            if (empty($input['id'])){
                $this->validate($input,PatrolChildValidate::class . '.list');
                if (!empty($input['patrol_id'])){
                    $where['m.patrol_id'] = $input['patrol_id'];
                }
                if (!empty($input['patrol_inspection_id'])){
                    $where['m.patrol_inspection_id'] = $input['patrol_inspection_id'];
                }
            }else {
                $where['m.id'] = $input['id'];
            }

            $data = $this->model->alias('m')
                ->join('user_shop s','s.id=m.shop_id')
                ->where($where)
                ->field('m.*,s.name as shop_name,s.coverimage as shop_coverimage,
                s.city as shop_city,s.merchant_address as shop_address,
                s.lnglat as shop_lnglat
                ')
                ->order('sort desc')
                ->select();
            $this->success('ok', $data);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }




    /**
     * 支队长督察任务
     */
    public function save_supervisions_status()
    {
        $input = input();
        $userinfo = $this->auth->getUserinfo();
        if ($userinfo['type'] != 3) {
            throw  new Exception('当前用户身份无权限');
        }
        try {
            $this->validate($input, PatrolValidate::class . '.save_status');
            $startstatus =  $this->model->where('id', $input['id'])
                ->field('patrol_id,supervisions_status')->find();
            if (!$startstatus){
                throw new Exception('未找到任务');
            }
            if ($startstatus['supervisions_status'] > 1){
                throw new Exception('当前任务已经在督察');
            }
            $patrol = $this->model->where('id', $input['id'])
                ->update(['supervisions_status' => 2,'user_staff_id' => $userinfo['staff_id']]);
            if (!$patrol) {
                throw  new Exception('督察失败');
            }
            $this->modelLog->add($startstatus['patrol_id'],'支队长开始督察任务');

            $this->success('保存成功', ['id' => $input['id']]);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }



    /**
     * 支队长督察列表
     * @return void
     */
    public function supervise_list()
    {
        try {
            $data = $this->model->alias('m')
                ->join('user_shop s','s.id=m.shop_id')
                ->where(['m.user_staff_id' => $this->auth->getUserinfo()['staff_id']])
                ->field('m.*,s.name as shop_name,s.coverimage as shop_coverimage')
                ->order('id desc')
                ->select();
            $this->success('ok', $data);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }


    /**
     * 任务排序
     * @return void
     */
    public function save_sort()
    {
        $input = input();
        try {
            if (empty($input['id']) || empty($input['sort'])){
                throw new Exception('信息错误');
            }
            $this->model->where(['id' => $input['id']])
                ->update(['sort' => $input['sort']]);
            $this->success('保存成功',['id' => $input['id']]);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }




    /**
     * 巡查打卡详情
     * @return void
     */
    public function info()
    {
        $input = input();
        try {
            if (!empty($input['id'])){
                $where = ['id' => $input['id']];
            }
            $data = $this->model->alias('m')
                ->join('user_shop s','s.id=m.shop_id')
                ->where($where)
                ->field('m.*,s.name as shop_name,s.coverimage as shop_coverimage,
                s.city as shop_city,s.merchant_address as shop_address,
                s.lnglat as shop_lnglat
                ')
                ->order('sort desc')
                ->find();
            $this->success('ok',$data);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 巡查打卡
     * @return void
     */
    public function save_submit(){
        $input = input('post.');
        try {
            $this->validate($input,PatrolChildValidate::class.'.save_submit');

            $info = $this->model->where('id', $input['id'])->find();
            if (!$info) {
                throw new Exception('未找到信息');
            }
            if ($info['endstatus'] != 1 || $info['status'] != 1) {
                throw new Exception('巡查任务已打卡');
            }
            //如果案件开始确认开始， 最后已个结束
            $this->model->savesSubmit($input['id'],$info['patrol_id'],[
                'images' => $input['images'],
                'endstatus' => $input['endstatus'],
                'mome' => $input['memo'],
                'startime' => $input['startime'],
                'money' => $input['money'] ?? '0.00',
                'cases_type_id' => $input['cases_type_id'] ?? '',
            ]);



            //不合格生成案件
            if ((int)$input['endstatus'] === 3){
                $patrol_info = $this->modelPatrol->where('id' , $info['patrol_id'])->find();
                $this->modelCases->insert([
                    'type' => $input['nature_type'],
                    'user_shop_id' => $info['shop_id'],
                    'user_staff_id' => $patrol_info['user_staff_id'],
                    'detachment_id' => $patrol_info['detachment_id'],
                    'captain_id' => $patrol_info['captain_id'],
                    'cases_type_id' => $input['cases_type_id'],
                    'user_staff_class_id' => $this->auth->getUserinfo()['user_staff_class_id'],
                    'content' => $input['memo'],
                    'images' => $input['images'],
                    'money' => $input['money'],
                    'starttime' => $input['startime'],
                    'endtime' => date('Y-m-d H:i:s'),
                    'createtime' => time(), //创建时间
                    'patrol_child_id' => $input['id']
                ]);
            }
            $this->success('打卡成功',['id' => $input['id']]);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }


}